import urllib,urllib2,re,xbmcplugin,xbmcgui,os,time,sys
import plugin_helper

class YesManager:
  
  def __init__(self):
    self.MODES=plugin_helper.enum(GET_CATEGORIES_LIST=1,GET_SERIES_LIST=2,GET_EPISODES_LIST=3,PLAY=4)
  
  def work(self,mode,url='',name=''):
    if (mode==self.MODES.GET_CATEGORIES_LIST):
      self.getCategories()
    elif (mode==self.MODES.GET_SERIES_LIST):
      self.getSeriesList(url)
    elif(mode==self.MODES.GET_EPISODES_LIST):
      self.getEpisodeList(url,name)
    elif(mode==self.MODES.PLAY):
      plugin_helper.playRtmpFromUrl(url)
      
  def getCategories(self):
    genres={'1':'סדרות','2':'דוקו','4':'ילדים'}
    for i,t in genres.iteritems():
      plugin_helper.addDir('Yes',t,i,2,{"Title": t,"Genre":t})
    
  def getSeriesList(self,genre):
    matches = plugin_helper.getMatches("http://yes.walla.co.il/?w=0/7701",'<a class="Item_Menu" id="(\d+)" href="" onclick="itemsFetchRows\(this\.id,'+str(genre)+',0\); return\(false\);">(.*?)</a>')
    genres={'1':'series','2':'docu','4':'kids'}
    for url,name in matches:
      imgPath = plugin_helper.getPath('cache','headers','yes',name+".png")
      if not os.path.exists(imgPath):
        imgPath = "DefaultFolder.png"
      plugin_helper.addDir('Yes',name,str(genre)+"/"+url,3,{"Title": urllib.unquote(name),"Genre":genres[genre]},imgPath)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_GENRE)
    xbmcplugin.setContent(int(sys.argv[1]), 'tvshows')
    
  def getEpisodeList(self,url,name):
    matches  = self.getFromAjax('http://yes.walla.co.il/?w='+url)
    for href,name,tagline,thumb in matches:
      plugin_helper.addVideo('Yes',name,tagline,'http://yes.walla.co.il/'+href,4,{ "Title": urllib.unquote(name),"Tagline":urllib.unquote(tagline)},thumb)
    xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
    
    for x in range(1,29):
      xbmcplugin.addSortMethod(int(sys.argv[1]),x)
    
  
  def getFromAjax(self,url):
    match=[]
    length = 1
    i=0
    while (length>0 and i<=10):
      pat='<table cellpadding="0" cellspacing="0" class="buxaBg_2">\r\n\t<tr>\r\n\t\t<td  width=322 style="padding:8 0 7 6; " valign="top"><a href="(.*?)" class="w2b">(.*?)</a><br>(.*?)</td>\r\n\t\t<td valign="top" style="padding:7 6 7 6; width:97px;">  <table cellpadding=0 cellspacing=0 class="wtable wbgpos" background="(.*?)">'
      news = plugin_helper.getMatches(url+"/"+str(i)+"//@Ajax_display_full_chapters",pat)
      length=len(news)
      match+=news
      i+=1
    return match
